<?php
/**
 * @author GhostWei
 * @date Oct 14, 2012
 */
class resource_advertise_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('resource_advertise_row');
		$this->setModel('resource_advertise_model', 'advertise');
		$this->setJoinLeftModel('resource_file_model', 'file.hash = advertise.hash', 'file');
		$this->setJoinLeftModel('resource_link_model', 'link.key = advertise.link', 'link');
		$this->setModelCols('advertise', array('id', 'name', 'hash', 'link', 'width', 'height', 'description', 'creationtime'));
		$this->setModelCols('file', array('extension'));
		$this->setModelCols('link', array('key', 'url', 'click'));
	}
	
	public function save(resource_advertise_row $row) {
		if(!$row->getName()) {
			throw new resource_exception('advertisement name can not be empty.');
		}
		if(!$row->getWidth()) {
			$row->setWidth(0);
		}
		if(!$row->getHeight()) {
			$row->setHeight(0);
		}
		$key = '';
		if($row->getUrl()) {
			$key = system_encrypt::shortUrl($row->getUrl());
			$row->setKey($key);
		}
		$row->setLink($key);
		
		if($row->getId()) {
			if($this->getModel('advertise')->fetchRow(array('id != ?' => $row->getId(), 'name = ?' => $row->getName()))) {
				throw new resource_exception('this advertisement name is alreay exiting.');
			}
			$this->getModel('advertise')->update($row->getModelData('advertise'), array('id = ?' => $row->getId()));
		} else {
			if($this->getModel('advertise')->fetchRow(array('name = ?' => $row->getName()))) {
				throw new resource_exception('this advertisement name is alreay exiting.');
			}
			$row->setCreationtime(system_date::timestamp());
			$id = $this->getModel('advertise')->insert($row->getModelData('advertise'));
			$row->setId($id);
		}
				
		if($key) {
			if(!$this->getModel('link')->fetchRow(array('`key` = ?' => $key))) {
				$row->setClick(0);
				$this->getModel('link')->insert($row->getModelData('link'));
			}
		}
		return $row;
	}
	
	public function delete(resource_advertise_row $row, $options = array()) {
		$concept = new resource_advertise_item_concept();
		foreach($concept->fetchAll(array('item.advertise_id = ?' => $row->getId())) AS $ad) {
			$ad->delete($options);
		}
		parent::delete($row);
	}
	
}
